package com.example.traffic_learning;

import global.global;

import java.io.File;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.NativeCameraView;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class CameraActivity extends FragmentActivity implements CvCameraViewListener2 {
	private static final String TAG = "MainActivity";
	private static final String STATE_CAMERA_INDEX = "cameraIndex";
	
	private int mCameraIndex;
	
	private boolean mIsCameraFrontFacing;
	private boolean mIsPhotoPending;
	
	private CameraBridgeViewBase mCameraView;
	
	private BaseLoaderCallback mLoaderCallback = 
			new BaseLoaderCallback(this) {
				@Override
				public void onManagerConnected(final int status){
					switch(status){
					case LoaderCallbackInterface.SUCCESS:
						Log.d(TAG, "OpenCV loaded successfully");
						mCameraView.enableView();
						break;
					default:
						super.onManagerConnected(status);
						break;
					}
				}
			};
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Window window = getWindow();
        getActionBar().setTitle("Học luật giao thông đường bộ");
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
        if(savedInstanceState != null){
        	mCameraIndex = savedInstanceState.getInt(STATE_CAMERA_INDEX, 0);
        }else{
        	mCameraIndex = 0;
        }
        
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD){
        	CameraInfo cameraInfo = new CameraInfo();
        	Camera.getCameraInfo(mCameraIndex, cameraInfo);
        	mIsCameraFrontFacing = (cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT);
        }else{
        	mIsCameraFrontFacing = false;
        }
        
        mCameraView = new NativeCameraView(this, mCameraIndex);
        mCameraView.setCvCameraViewListener(this);
        
        setContentView(mCameraView);
        
        mCameraView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mIsPhotoPending = true;
			}
		});
        
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(event.getAction() == KeyEvent.ACTION_DOWN)
        {
            switch(keyCode)
            {
            case KeyEvent.KEYCODE_CAMERA:
            	mIsPhotoPending = true;
            	break;
            }
        }

        return super.onKeyDown(keyCode, event);
    }
	
    public void onSaveInstanceState(Bundle savedInstanceState) {
		// Save the current camera index.
		savedInstanceState.putInt(STATE_CAMERA_INDEX, mCameraIndex);
		super.onSaveInstanceState(savedInstanceState);
	}
    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        return true;
    }
    
    @Override
    public void onPause() {
	    if (mCameraView != null) {
	    	mCameraView.disableView();
	    }
	    super.onPause();
    }
    
    @Override
    public void onResume() {
	    super.onResume();
	    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9,
	    this, mLoaderCallback);
    }
    
    @Override
    public void onDestroy() {
	    super.onDestroy();
	    if (mCameraView != null) {
	    	mCameraView.disableView();
	    }
    }
    
	@Override
	public void onCameraViewStarted(int width, int height) {
		
	}

	@Override
	public void onCameraViewStopped() {
		
	}

	@Override
	public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
		final Mat rgba = inputFrame.rgba();
		
		if(mIsPhotoPending){
			mIsPhotoPending = false;
			takePhoto(rgba);
		}
		
		if(mIsCameraFrontFacing){
			Core.flip(rgba, rgba, 1);
		}
		return rgba;
	}
	
	private void takePhoto(final Mat rgba) {
		// TODO Auto-generated method stub
		final long currentTimeMillis = System.currentTimeMillis();
		final String appName = "Traffic Learning";
		final String galleryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
		final String albumPath = galleryPath + "/" + appName;
		File folder = new File(albumPath);
		if (!folder.exists()) {
	        folder.mkdir();
	    }
		String photoPath = albumPath + "/" + currentTimeMillis + ".png";
		
		final ContentValues values = new ContentValues();
		values.put(MediaStore.MediaColumns.DATA, photoPath);
		//values.put(Images.Media.MIME_TYPE, LabActivity.PHOTO_MINE_TYPE);
		values.put(Images.Media.TITLE, appName);
		values.put(Images.Media.DESCRIPTION, appName);
		values.put(Images.Media.DATE_TAKEN, currentTimeMillis);
		
		File album = new File(albumPath);
		//
		deleteDirectory(album);
		if(!album.isDirectory() && !album.mkdirs()){
			Log.e(TAG, "Failed to create album directory at" + albumPath);
			onTakePhotoFailed();
			return;
		}
		Mat mBgr = new Mat();
		Imgproc.cvtColor(rgba, mBgr, Imgproc.COLOR_RGBA2BGR, 3);
		if (!Highgui.imwrite(photoPath, mBgr)) {
			Log.e(TAG, "Failed to save photo to " + photoPath);
			onTakePhotoFailed();
		}
		Log.d(TAG, "Photo saved successfully to " + photoPath);
		global.isCameraStart = true;
		global.imagePath = photoPath;
		Intent nextActivity = new Intent(this, MainActivity.class);
		finish();
		nextActivity.putExtra("possition", 5);
		startActivity(nextActivity);
		//
	}
	
	private void onTakePhotoFailed() {
		// TODO Auto-generated method stub
		// Show an error message.
		final String errorMessage ="Thiết bị chưa có thẻ nhớ, vui lòng gắn thẻ nhớ để tiếp tục";
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(CameraActivity.this, errorMessage,
						Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	private boolean deleteDirectory(File path) {
	    if( path.exists() ) {
	    	File[] files = path.listFiles();
	    	if (files == null) {
	    		return true;
	    	}
	    	for(int i=0; i<files.length; i++) {
	    		if(files[i].isDirectory()) {
	    			deleteDirectory(files[i]);
	    		}
	    		else {
	    			files[i].delete();
	    		}
	    	}
	    }
	    return( path.delete() );
	}
	@Override
	public void onBackPressed() {
		global.isCameraStart = false;
		Intent nextActivity = new Intent(this, MainActivity.class);
		finish();
		nextActivity.putExtra("possition", 5);
		startActivity(nextActivity);
	}
}
